package com.gxc.dbcore.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import com.gxc.dbcore.cache.EntityCache;
import com.gxc.webcore.util.StringUtil;

public class EntityDef {

	/**
	 * 实体对应的class
	 */
	private Class<?> clazz;

	/**
	 * 模式名
	 */
	private String schema;

	/**
	 * 表名
	 */
	private String table;

	/**
	 * 主键（实体id）
	 */
	private String id;

	/**
	 * 列数组（包括主键）
	 */
	private List<String> properties;

	public Class<?> getClazz() {
		return clazz;
	}

	public void setClazz(Class<?> clazz) {
		this.clazz = clazz;
	}

	public String getSchema() {
		if (StringUtil.isTrimEmpty(schema)) {
			schema = null;
		}
		return schema;
	}

	public void setSchema(String schema) {
		this.schema = schema;
	}

	public String getTable() {
		return table;
	}

	public void setTable(String table) {
		this.table = table;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<String> getProperties() {
		return properties;
	}

	public void setProperties(List<String> properties) {
		this.properties = properties;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List getKeyValueList(Object object) {
		List list = new ArrayList();
		if (object != null) {
			EntityDef entityDef = EntityCache.getEntityDef(object.getClass());
			BeanWrapper beanWrapper = new BeanWrapperImpl(object);
			for (String name : entityDef.getProperties()) {
				Map item = new HashMap();
				item.put("key", name);
				item.put("value", beanWrapper.getPropertyValue(name));
				list.add(item);
			}
		}
		return list;
	}

	public Object getIdValue(Object object) {
		if (object != null) {
			EntityDef entityDef = EntityCache.getEntityDef(object.getClass());
			BeanWrapper beanWrapper = new BeanWrapperImpl(object);
			return beanWrapper.getPropertyValue(entityDef.getId());
		}
		return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List getKeyValueList(Map map) {
		List list = new ArrayList();
		if (map != null) {
			for (String property : this.getProperties()) {
				Object value = map.get(property);
				Map item = new HashMap();
				item.put("key", property);
				item.put("value", value);
				list.add(item);
			}
		}
		return list;
	}

	@SuppressWarnings("rawtypes")
	public Object getIdValue(Map map) {
		if (map != null) {
			return map.get(this.getId());
		}
		return null;
	}

}
